﻿/// <reference path="jquery-vsdoc.js" />
/// <reference path="jquery.js" />
/// <reference path="jquery-ui.min.js" />
/// <reference path="jquery.validate.js" />
var retorno = false;
var id;

$(function () {
	if ($('#txtPesquisa') != undefined) {
		incluiLegenda('txtPesquisa');
		$('#txtPesquisa').focus();
	}
	$('.datepicker').each(function () {
		$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
		$(this).datepicker({
			showOn: 'focus',
			onClose: function () { this.focus(); },
			onSelect: function () { this.focus(); }
		});
	});
	$('.textarea').each(function () {
		var max = $(this).attr("maxlength");
		var idEl = $(this).attr("id");
		textarea_maxlength(idEl, max);
	});
});

jQuery.fn.center = function () {
    /// <summary>
    ///     Posiciona o elemento no centro da tela
    /// </summary>	
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

//function styleButtons() {
//	$('input:button, input:submit').button();
//}

function toogleClassValid(input, span, valid) {
    if (valid) {
        $(input).removeClass("input-validation-error");
        $(span).removeClass("field-validation-error").addClass("field-validation-valid").html("");
    } else {
        $(input).addClass("input-validation-error");
        $(span).removeClass("field-validation-valid").addClass("field-validation-error").html("*");
    }
}

function confirmDialog(idDialog, metodo, title, height, width, closeText) {
    $('#' + idDialog + ":ui-dialog").dialog("destroy");
    if (height == undefined || height == '') {
        if ($.browser.mozilla) { height = 230; }
        if ($.browser.webkit || $.browser.msie) { height = 220; }
    }
    if (width == undefined || width == '') {
        if ($.browser.mozilla) { width = 360; }
        if ($.browser.webkit || $.browser.msie) { width = 350; }
    }
    if (title == undefined || title == '') {
        title = '<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 0 0;"></span>Atenção! Exclusão de registro!';
    }
    else {
        title = '<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 0 0;"></span>' + title;
    }
    if (closeText == undefined || closeText == '') { closeText = 'hide'; }
    $('#' + idDialog).dialog({
        resizable: false,
        height: height,
        width: width,
        modal: true,
        title: title,
        close: function (event, ui) {
            $('#' + idDialog + ":ui-dialog").dialog("destroy");
        },
        buttons: {
            "Ok": function () {
                $(this).dialog("close");
                switch (metodo) {
                    default: excluir();
                        break;
                    case 'excluirUser': excluirUser();
                        break;
                }
            },
            "Cancelar": function () {
                retorno = false;
                $(this).dialog("close");
            }
        }
    });
}

function alertDialog(idDialog, title, height, width, closeText) {
    $('#' + idDialog + ":ui-dialog").dialog("destroy");
    if (height == undefined || height == '') {
        if ($.browser.mozilla) { height = 230; }
        if ($.browser.webkit || $.browser.msie) { height = 220; }
    }
    if (width == undefined || width == '') {
        if ($.browser.mozilla) { width = 360; }
        if ($.browser.webkit || $.browser.msie) { width = 350; }
    }
    if (title == undefined || title == '') {
        title = '<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 0 0;"></span>Atenção!';
    }
    else {
        title = '<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 0 0;"></span>' + title;
    }    
    $('#' + idDialog).dialog({
        resizable: false,
        height: height,
        width: width,
        modal: true,
        title: title,
        close: function (event, ui) {
            $('#' + idDialog + ":ui-dialog").dialog("destroy");
        },
        buttons: {
            "Ok": function () {
                $(this).dialog("close");
            }
        }
    });
}

function formDialog(idDialog, title, height, width, gravar, cancelar) {
    idDialog = '#' + idDialog;
    $(idDialog + ":ui-dialog").dialog("destroy");
    if (height == undefined || height == '') {
        if ($.browser.mozilla) { height = 230; }
        if ($.browser.webkit || $.browser.msie) { height = 220; }
    }
    if (width == undefined || width == '') {
        if ($.browser.mozilla) { width = 360; }
        if ($.browser.webkit || $.browser.msie) { width = 350; }
    }
    if (title == undefined || title == '') { title = 'Cadastro'; }
    if (gravar == undefined || gravar == '') { gravar = "Gravar"; }
    if (cancelar == undefined || cancelar == '') { cancelar = "Cancelar"; }
    $(idDialog).dialog({
        resizable: false,
        height: height,
        width: width,
        modal: true,
        close: function (event, ui) {
            var form = $(idDialog + ">#formHide");
            form.remove();
            $(idDialog + ":ui-dialog").dialog("destroy");
        },
        title: title
    });
}

function textarea_maxlength(idEl, max) {
    var campo = $('#' + idEl);
    campo.keypress(function (event) {
        var key;
        var ie = (typeof window.ActiveXObject != 'undefined');
        (ie) ? key = event.keyCode : key = event.which; // Se for IE (keyCode), caso contrario, (wich)  
        if (key >= 33 || key == 13 || key == 32) {
            // Se ja estiver no limite de caracteres return null (preventDefault)
            var tam = this.value.length;
            (tam >= max) ? event.preventDefault() : null;
        }
        window.status = campo.val().length;
    });

    // Substring no evento keyup
    campo.bind('keyup', function (event) {
        var tam = this.value.length;
        if (tam > max) {
            campo.val(campo.val().substring(0, max));
            //setcursor(idEl,1000000,1000000);
        }
    });
}

function onRowSelected(e) {
    var grid = $(this).data('tGrid');    
    var colunas = e.row.cells;    
    var css = e.row.cells[0].className;
    if (css != "t-group-cell") {
        id = colunas[0].innerHTML;        
        return false;
    }
}

function PesquisaOnRowSelected(e) {
    var grid = $(this).data('tGrid');
    var colunas = e.row.cells;
    var css = e.row.cells[0].className;
    if (css != "t-group-cell") {
        id = colunas[0].innerHTML;
        return false;
    }
}

function Grid_onLoad(e) {
    dblClick(this);
}

function Grid_onLoad(e, grid) {
    dblClick(grid);
}

function Grid_onLoad(e, grid, btnAlterar) {
    dblClick(grid, btnAlterar);
}

function PesquisaGrid_onLoad(e) {
    dblClick(e, this, 'Selecionar');
}

function dblClick(g, btnAlterar) {
    $('tbody > tr:not(.t-grouping-row)', g).live('dblclick', function (e) {
        if (btnAlterar == undefined) {
            $("#Alterar").click();
        }
        else {
            $("#" + btnAlterar).click();
        }
    })
}

function gridRebind(idGrid) {
    $('#' + idGrid).data('tGrid').rebind();
    id = undefined;
}

function showLoading() {
    var css = ($(window).height() - $('#load').height() /2 ) / 2 + $(window).scrollTop() + "px";
    $('#load').css('top', css).show();
}

function hideLoading() {
    $('#load').hide();
}

function alertError(erros) {
    var html = 'Ocorreram os seguintes erros: <br /><br />';
    if (erros) {
        html += erros;
    } else {
        html += "Não foi possível se comunicar com o servidor!";
    }
    $('#alertaErro').html(html);
    alertDialog('alertaErro', 'Erro!');
}

function incluiLegenda(el) {
    if ($('#' + el).val() == '') {
        $('#' + el).val('Digite sua pesquisa');
        $('#' + el).addClass('legendaPesquisa');
    }
    return false;
}

function retiraLegenda(el) {
    if ($('#' + el).val() == 'Digite sua pesquisa') {
        $('#' + el).val('');
        $('#' + el).removeClass('legendaPesquisa').select();
    }
    return false;
}

$('#txtPesquisa').focus(function (e) {
    retiraLegenda('txtPesquisa');
    e.preventDefault();
});

$('#txtPesquisa').blur(function (e) {
    incluiLegenda('txtPesquisa');
    e.preventDefault();
});

function validaData(input){
    var minDate = $(input).attr("mindate");
    var maxDate = $(input).attr("maxdate");
    var date = $(input).val();
    var span = $(input).next();
    if (date <= minDate) {
        toogleClassValid(input, span, false);
        return false;
    } else if (date > maxDate) {
        toogleClassValid(input, span, false);
        return false;
    } else {
        toogleClassValid(input, span, true);
        return true;
    }
}

function validaDataMaior(dataInicioEl, dataFimEl) {
    var dataInicio = $(dataInicioEl).val();
    var dataFim = $(dataFimEl).val();
    var dt = dataInicio.split("/");
    dataInicio = new Date(dt[2], dt[1] - 1, dt[0]);
    dt = dataFim.split("/");
    dataFim = new Date(dt[2], dt[1] - 1, dt[0]);
    var spanDataInicio = $(dataInicioEl).next();
    var spanDataFim = $(dataFimEl).next();
    if (dataInicio > dataFim) {
        toogleClassValid(dataInicioEl, spanDataInicio, false);
        toogleClassValid(dataFimEl, spanDataFim, false);
        return false;
    } else {
        toogleClassValid(dataInicioEl, spanDataInicio, true);
        toogleClassValid(dataFimEl, spanDataFim, true);
        return true;
    }
}

/* Brazilian initialisation for the jQuery UI datepicker plugin. */
/* Written by Leonildo Costa Silva (leocsilva@gmail.com). */
jQuery(function ($) {
    $.datepicker.regional['pt-BR'] = {
        closeText: 'Fechar',
        prevText: '&#x3c;Anterior',
        nextText: 'Pr&oacute;ximo&#x3e;',
        currentText: 'Hoje',
        monthNames: ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho',
                'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun',
                'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
        dayNames: ['Domingo', 'Segunda-feira', 'Ter&ccedil;a-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sabado'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 0,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['pt-BR']);
});